﻿using System;
using System.IO;
using System.Linq;
using System.Web;

using Telerik.Sitefinity.Abstractions;
using Telerik.Sitefinity.Modules.Pages;
using Telerik.Sitefinity.Pages.Model;

namespace Migration.Classes
{
	public static class MigrationTemplates
	{
		private static PageManager m_PageManager;

		static MigrationTemplates()
		{
			m_PageManager = PageManager.GetManager();
		}

		public static void ImportTemplate(Telerik.Sitefinity.Services.Migration.MigrationTemplate templateContent)
		{
			if (m_PageManager.Provider == null)
			{
				m_PageManager = PageManager.GetManager();
			}

			Guid id = templateContent.Id;
			string name = templateContent.Name;
			string themeName = templateContent.Theme;

			var currentCulture = System.Threading.Thread.CurrentThread.CurrentUICulture;
			System.Threading.Thread.CurrentThread.CurrentUICulture = MigrationCultures.DefaultCulture;

			// Check if the template already exists
			PageTemplate checkItem = m_PageManager.GetTemplates().Where(t => t.Id == id).FirstOrDefault();
			if (checkItem != null)
			{
				MigrationLogger.AppendLogMessage(String.Format("Skipping template \"<b>{0}</b>\", already exists.", name) + "<br/>");
				return;
			}

			MigrationLogger.AppendLogMessage(String.Format("Importing template \"<b>{0}</b>\"...<br/>", name));

			string appMasterPath = String.Empty;
			string primaryMasterPageName = String.Empty;

			foreach (var masterPage in templateContent.MasterPages)
			{
				foreach (var userControl in masterPage.UserControls)
				{
					string fullPath = HttpContext.Current.Server.MapPath(userControl.AscxFilePath);
					if (!File.Exists(fullPath))
					{
						Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
						File.WriteAllText(fullPath, userControl.AscxFileContent);
						if (!String.IsNullOrEmpty(userControl.AscxFileCondeBehindContent))
						{
							File.WriteAllText(Path.GetDirectoryName(fullPath) + "\\" + userControl.AscxCodeBehindFileName, userControl.AscxFileCondeBehindContent);
						}

						// Try to create an instance of this user control to see if it is safe to include it
						UserControlLoadState loadResult = UserControlLoadState.NoErrors;
						try
						{
							var testObj = MigrationSettings.ModulePage.LoadControl(userControl.AscxFilePath);
						}
						catch (HttpCompileException)
						{
							loadResult = UserControlLoadState.CodeBehindError;
						}
						catch (HttpParseException)
						{
							// HttpParseExceptions are generally OK
							loadResult = UserControlLoadState.AscxError;
						}

						if (loadResult == UserControlLoadState.NoErrors)
						{
							MigrationSettings.WhiteListedUserControlPaths.Add(userControl.AscxFilePath.ToUpperInvariant());
						}
						else if (MigrationSettings.RewriteRegisterTags)
						{
							File.WriteAllText(fullPath, MigrationControls.ParseMasterAspxAscxContent(userControl.AscxFileContent));
						}
					}
				}

				string masterPageName = masterPage.MasterPageName;
				appMasterPath = "~/App_Master";

				if (masterPage.IsPrimary)
				{
					primaryMasterPageName = masterPageName;
				}

				if (!String.IsNullOrEmpty(themeName))
				{
					appMasterPath = String.Format("~/App_Data/Sitefinity/WebsiteTemplates/{0}/App_Master", themeName);
				}

				string appMasterPathPhysical = HttpContext.Current.Server.MapPath(appMasterPath);

				if (!Directory.Exists(appMasterPathPhysical))
				{
					Directory.CreateDirectory(appMasterPathPhysical);
				}

				string masterPagePath = String.Format("{0}\\{1}", appMasterPathPhysical, masterPageName);

				if (!File.Exists(masterPagePath))
				{
					string fileContent = masterPage.MasterPageContents;
					if (MigrationSettings.RewriteRegisterTags)
					{
						fileContent = MigrationControls.ParseMasterAspxAscxContent(masterPage.MasterPageContents);
					}

					File.WriteAllText(masterPagePath, fileContent);
				}
			}

			PageTemplate newTemplate = m_PageManager.CreateTemplate(id);
			newTemplate.Category = SiteInitializer.CustomTemplatesCategoryId;
			newTemplate.LastModified = templateContent.DateModified;
			if (!String.IsNullOrEmpty(primaryMasterPageName))
			{
				newTemplate.MasterPage = String.Format("{0}/{1}", appMasterPath, primaryMasterPageName);
			}
			newTemplate.Name = name;
			newTemplate.Owner = MigrationUsers.DefaultOwner;
			newTemplate.Title[MigrationCultures.DefaultCulture] = newTemplate.Name;
			newTemplate.Theme = templateContent.Theme;
			newTemplate.Version = templateContent.Version;

			// Add permissions to the controls
			//MigrationControls.AddPermissionForEveryone<TemplateControl>(newTemplate.Controls, m_PageManager);

			m_PageManager.SaveChanges();

			// Parse the controls
			for (int i = 0; i < templateContent.Controls.Count; i++)
			{
				string result = MigrationControls.InsertControlToCollection<TemplateControl>(newTemplate.Controls, templateContent.Controls[i], true);
				MigrationLogger.AppendLogMessage(result);
			}

			System.Threading.Thread.CurrentThread.CurrentUICulture = currentCulture;
		}
	}
}
